﻿using System;
using System.Text;
using Newtonsoft.Json;

namespace housingsafety.server.Caching.Core
{
    public class JsonCacheSerializer : ICacheSerializer
    {
        private readonly JsonSerializerSettings m_JsonSerializerSettings;

        public JsonCacheSerializer(JsonSerializerSettings jsonSerializerSettings = null)
        {
            m_JsonSerializerSettings = jsonSerializerSettings ?? new JsonSerializerSettings();
        }

        public TItem Deserialize<TItem>(byte[] data)
        {
            var stringValue = Encoding.UTF8.GetString(data);
            return JsonConvert.DeserializeObject<TItem>(stringValue, m_JsonSerializerSettings);
        }

        public object Deserialize(byte[] data, Type type = null)
        {
            var stringValue = Encoding.UTF8.GetString(data);
            if (type == null)
                return JsonConvert.DeserializeObject(stringValue, m_JsonSerializerSettings);

            return JsonConvert.DeserializeObject(stringValue, type, m_JsonSerializerSettings);
        }

        public byte[] Serialize<TItem>(TItem item)
        {
            var stringValue = JsonConvert.SerializeObject(item, m_JsonSerializerSettings);
            return Encoding.UTF8.GetBytes(stringValue);
        }
    }
}
